﻿using System;
using System.Net;
using System.Net.Sockets;

namespace Fadd.Components.Remoting
{
	/// <summary>
	/// Hosting remoting commands.
	/// </summary>
	public class RemotingServer
	{
		private IPEndPoint _endPoint;
		private readonly ComponentManager _components;
		private TcpListener _listener;

		/// <summary>
		/// Initializes a new instance of the <see cref="RemotingServer"/> class.
		/// </summary>
		/// <param name="components">The components.</param>
		public RemotingServer(ComponentManager components)
		{
			_components = components;
		}

		/// <summary>
		/// Start channel
		/// </summary>
		/// <param name="value">End point to connect to or listen on.</param>
		public void Start(IPEndPoint value)
		{
			_endPoint = value;
			StartListener(value);
		}

		private void StartListener(IPEndPoint value)
		{
			_listener = new TcpListener(value);
			_listener.Start();
			_listener.BeginAcceptSocket(OnAcceptClient, null);
		}

		private void OnAcceptClient(IAsyncResult ar)
		{
			try
			{
				Socket socket = _listener.EndAcceptSocket(ar);
				RemotingChannel channel = new RemotingChannel(_components, socket);
			}
			catch(Exception err)
			{
				
			}

			try
			{
				_listener.BeginAcceptSocket(OnAcceptClient, null);
			}
			catch(Exception err)
			{}

		}

		public void Stop()
		{
			if (_listener != null)
			{
				_listener.Stop();
				_listener = null;
			}			
		}

	}
}
